import {isMobilePhone} from '../../utils/utils'
// 表单
interface IFormProps {
  style?: string;
  formItems: FormBase.IFormItem[];
  labelWidth?: number;
  onBlur?(data: { value: string; key: string }): void;
  onInput?(data: { value: string; key: string }): void;
}
interface IFormData {
  formDataMap: object;
  isIOS: boolean
}
interface IFormMethods {
  handleInputChange(e): void;
  checkValue(): void;
}
Component<IFormData, IFormProps, IFormMethods>({
  data: {
    formDataMap: {},
    isIOS: false,
  },
  props: {
    formItems: []
  },
  onInit() {
    this.setData({
      isIOS: my.env.platform === 'iOS'
    })
  },
  methods: {
    // 表单检验
    checkValue() {
      return new Promise((resolve, reject) => {
        const { formItems } = this.props;
        const {formDataMap } = this.data
        for (let i = 0; i < formItems.length; i++) {
          const item = formItems[i]
          formDataMap[item.key] =  formDataMap[item.key] || item.value
          if (item.require && !formDataMap[item.key]) {
            my.showToast({
              content: `请输入${item.label}`
            })
            reject()
            return
          }
          if (item.require && item.isMobile && !isMobilePhone(formDataMap[item.key])) {
            my.showToast({
              content: `请输入正确的手机号`
            })
            reject()
            return
          }
        }
        resolve(formDataMap);
      });
    },
    handleInputChange({ detail: { value }, target: { id }, type }) {
      const data = {
        value,
        key: id
      };
      this.data.formDataMap[id] = value;
      if (type === "blur") {
        this.props.onBlur && this.props.onBlur(data);
      } else {
        this.props.onInput && this.props.onInput(data);
      }
    }
  }
});
